package cn.com.header.core.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * 日志工具类
 * Created by lhd on 2017/7/21.
 */
public class LogUtil {

    /**
     *
     * @param rootPath:文件根路径
     * @param fileName：文件名
     * @param msgList：文件写入信息提示
     * @param request
     * @param response
     * @throws Exception
     */
    public static void writeLogFile(String rootPath, String fileName, List<String> msgList, HttpServletRequest request, HttpServletResponse response) throws Exception{
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String filePath = request.getServletContext().getRealPath(rootPath+fileName);
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileWriter output = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(output);
        for (int i = 0; i < msgList.size(); i++) {
            bw.write(msgList.get(i) + "\r\n");
            bw.flush();
        }
        bw.close();
    }

    /**
     * 日志文件下载
     * @param filePath：文件根路径
     * @param fileName：文件名
     * @param request
     * @param response
     * @throws Exception
     */
    public static void downloadLog(String filePath, String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        String filepath = request.getServletContext().getRealPath(filePath+fileName);
        //设置response的头信息
        response.setHeader("Content-disposition","attachment;filename=\""+fileName+"\"");
        InputStream is = null;
        OutputStream os = null;
        try{
            is = new BufferedInputStream(new FileInputStream(filepath));
            //定义输出字节流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //定义response的输出流
            os = new BufferedOutputStream(response.getOutputStream());
            //定义buffer
            byte[] buffer = new byte[4*1024]; // 4k Buffer
            int read = 0;
            //从文件中读入数据并写到输出字节流中
            while((read=is.read(buffer))!=-1){
                baos.write(buffer,0,read);
            }
            //将输出字节流写到response的输出流中
            os.write(baos.toByteArray());
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            //关闭输出字节流和response输出流
            os.close();
            is.close();
        }
    }

}
